#include"AbstractLayer.h"
#include"LSYEasyBody.h"
#include"LSYEasyWorld.h"
#include"GLES-Render.h"
#include"Tool.h"

USING_NS_CC;

bool AbstractLayer::init(const b2Vec2 & gravity)
{
	if (!Layer::init())
	{
		return false;
	}
	createBox2dApp(gravity);
	box2DAppReady();
	scheduleUpdate();
	setTouchEnabled(true);
	auto listener = EventListenerTouchOneByOne::create();
	listener->onTouchBegan = CC_CALLBACK_2(AbstractLayer::onTouchBegan, this);
	listener->onTouchEnded = CC_CALLBACK_2(AbstractLayer::onTouchEnded, this);
	listener->onTouchMoved = CC_CALLBACK_2(AbstractLayer::onTouchMoved, this);

	auto listener2 = EventListenerKeyboard::create();
	listener2->onKeyPressed = [this](EventKeyboard::KeyCode keyCode, Event * event)
	{
		onKeyPressed(keyCode, event);
	};
	listener2->onKeyReleased = [this](EventKeyboard::KeyCode keyCode, Event * event)
	{
		onKeyReleased(keyCode, event);
	};
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener2, this);
	return true;
}

void AbstractLayer::createBox2dApp(const b2Vec2 & gravity)
{
	pWorld = LSYEasyWorld::createWorld(gravity);
	pDebug = LSYEasyWorld::createDebug();
}

void AbstractLayer::update(float dt)
{
	LSYEasyWorld::updateWorld();
}

void AbstractLayer::box2DAppReady()
{
	
}

void AbstractLayer::onExit()
{
	REALSE_NULL(pWorld);
}

bool AbstractLayer::onTouchBegan(cocos2d::Touch * touch, cocos2d::Event * unused_event)
{
	return true;
}

void AbstractLayer::onTouchEnded(cocos2d::Touch * touch, cocos2d::Event * unused_event)
{
}

void AbstractLayer::onTouchMoved(cocos2d::Touch * touch, cocos2d::Event * unused_event)
{
}

void AbstractLayer::onKeyPressed(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event * event)
{
	
}

void AbstractLayer::onKeyReleased(cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event * event)
{
	
}

void AbstractLayer::draw(cocos2d::Renderer * renderer, const cocos2d::Mat4 & transform, uint32_t flags)
{
	Node::draw(renderer, transform, flags);
	ccGLEnableVertexAttribs(kCCVertexAttribFlag_Position);
	kmGLPushMatrix();
	pWorld->DrawDebugData();
	kmGLPopMatrix();
	CHECK_GL_ERROR_DEBUG();
}
